<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/axios@1.6.5/dist/axios.min.js"></script>
  </head>
  <body>
    <input id="fileInput" type="file" />
    <button id="signature">getSignature</button>
    <script>
      const fileInput = document.getElementById('fileInput');

      async function getOSSInfo() {
        const res = await fetch('http://localhost:3005/api/oss/signature');
        const data = await res.json();
        console.log('====getOSSInfo====');
        console.log(data);
        return data;
        // return {
        //   OSSAccessKeyId: 'LTAI5tDemEBPwQkTx65jZCdy',
        //   Signature: 'NfXgq/qLIR2/v87j/XC9sjrASOA=',
        //   policy:
        //     'eyJleHBpcmF0aW9uIjoiMjAyNC0wMS0yMFQwMzoyNjowOC4xMDZaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==',
        //   host: 'http://guang-333.oss-cn-beijing.aliyuncs.com',
        // };
      }
      let ossInfo = {};
      document.getElementById('signature').onclick = async () => {
        ossInfo = await getOSSInfo();
        console.log(ossInfo);
      };

      fileInput.onchange = async () => {
        const file = fileInput.files[0];

        const formdata = new FormData();

        formdata.append('key', file.name);
        formdata.append('OSSAccessKeyId', ossInfo.OSSAccessKeyId);
        formdata.append('policy', ossInfo.policy);
        formdata.append('signature', ossInfo.Signature);
        formdata.append('success_action_status', '200');
        formdata.append('file', file);

        const res = await axios.post(ossInfo.host, formdata);
        console.log(res);
        if (res.status === 200) {
          const img = document.createElement('img');
          img.src = ossInfo.host + '/' + file.name;
          document.body.append(img);

          alert('上传成功');
        }
      };
    </script>
  </body>
</html>
